package com.xinghanlaser.applet.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/7 11:49
 */
public class NewMeMetaObjectHandler implements MetaObjectHandler {
    public static final String CREATE_TIME = "createTime";
    public static final String CREATE_USER = "createUser";
    public static final String UPDATE_TIME = "updateTime";
    public static final String UPDATE_USER = "updateUser";

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName(CREATE_TIME, DateUtil.now(), metaObject);
        this.setFieldValByName(UPDATE_TIME, DateUtil.now(), metaObject);

        Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .map(item -> (String)item.getPrincipal())
                .ifPresent(userName -> this.setFieldValByName(CREATE_USER, userName, metaObject));

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName(UPDATE_TIME, DateUtil.now(), metaObject);

        Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .map(item -> (String)item.getPrincipal())
                .ifPresent(userName -> this.setFieldValByName(UPDATE_USER, userName, metaObject));
    }
}
